# -*- coding: utf-8 -*-
"""
@Time    : 2020/8/3 17:55
@Author  : Corey
"""
from PyQt5.QtCore import QRunnable, QWaitCondition, QMutex, pyqtSignal, QObject
import velox


class Signal(QObject):
    TestSignal = pyqtSignal(dict)
    Pulse = pyqtSignal(int)
    Stop = pyqtSignal(int)
    End = pyqtSignal(int)
    err_signal = pyqtSignal(object)


class WaferThread(QRunnable):

    def __init__(self):  # , path_folder, file_name
        super(WaferThread, self).__init__()
        self.cond = QWaitCondition()
        self.mutex = QMutex()
        self.sign = Signal()
        self.statu = 0
        self._isPause = False
        self.map_statu = 0
        self.__bin_color = 0
        self.time_statu = 1
        self.flag = True

    def run(self):
        try:
            with velox.MessageServerInterface(ipaddr="192.168.5.20", targetSocket=1421) as msgServer:
                velox.IsAppRegistered('Kernel')
                rsp = velox.GetWaferInfo()
                die_total = rsp.DiesCount
                velox.ClearAllBins()
                velox.GoToWaferHome()
                rsp = velox.StepFirstDie()
                subDie = rsp.CurSite
                while self.flag:
                    self.mutex.lock()
                    rsp = velox.ReadMapPosition()
                    self.sign.TestSignal.emit({"x": rsp.DieX, "y": rsp.DieY, "curDie": rsp.CurDie,
                                               "process": (rsp.CurDie / die_total) * 100, "TaskCount": die_total,
                                               "subDie": subDie})
                    self.pause()
                    if self._isPause:
                        self.cond.wait(self.mutex)
                    velox.BinMapDie(self.__bin_color)
                    velox.StepNextDie()
                    self.mutex.unlock()
        except velox.SciException as e:
            if e.code == '703':
                self.sign.End.emit(1)
            elif e.code == '512':
                print('There was an error. The error code was %s.' % e.code)
                print('This may mean that the WaferMAp application is not running.')
                print('Make sure that the WaferMap application is running and try again.')
                self.sign.err_signal.emit(str(e))

            else:
                self.sign.err_signal.emit(str(e))
                print('We caught an exception with error code %s as:' % e.code)


        except Exception as e:
            self.sign.err_signal.emit(str(e))

    def pause(self):
        self._isPause = True

    def resume(self):
        self._isPause = False
        self.cond.wakeAll()

    def set_bin_color(self, bin_color):
        self.__bin_color = bin_color

    def cancel_thread(self):
        self.flag = False
